package com.even.camerarecoder.aac

import com.evendai.loglibrary.Timber
import java.nio.ByteBuffer
import java.util.concurrent.BlockingQueue
import java.util.concurrent.LinkedBlockingQueue

/**
 * AAC编码器线程
 * @param sampleRateInHz 指定PCM音频数据的采样率
 * @param channelCount 指定PCM音频数据的通道数量
 * @param maxInputSize 指定每次送入AAC编码器的PCM音频数据的最大大小
 */
class AACEncoderThread(sampleRateInHz: Int, channelCount: Int, maxInputSize: Int): Thread(
    AACEncoderThread::class.java.simpleName) {

    private val mAACEncoder = AACEncoder(sampleRateInHz, channelCount, maxInputSize)
    private var frameLossCount: Int = 0
    private var needRun = true

    private var mPCMDataQueue: BlockingQueue<ByteBuffer> = LinkedBlockingQueue(5)

    fun addPCMBytes(bytes: ByteBuffer) {
        if (needRun) {
            val offer = mPCMDataQueue.offer(bytes)
            if (!offer) {
                Timber.w("丢帧：${++frameLossCount}帧")
            }
        }
    }

    override fun run() {
        try {
            while (needRun) {
                mAACEncoder.encodePCMToAAC(mPCMDataQueue.take())
            }
        } catch (e: Exception) {
            Timber.fe(e,"把PCM编码为AAC时出现异常")
        }
    }

    fun close() {
        try {
            needRun = false
            mAACEncoder.close()
        } catch (e: Exception) {
            Timber.w(e,"关闭AAC编码器时出现异常")
        }
    }
}